package com.achen.elasticsearch.dao.impl;

import com.achen.elasticsearch.dao.DeptRepository;
import com.achen.entity.Dept;
import com.achen.entity.Result;
import com.achen.service.DeptService;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author achen
 * @create 2020-04-29 21:40
 */
@Repository
public class DeptRepositoryImpl implements DeptRepository {

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public Map findBySearch(String querykeyword, Integer page, Integer limit) {
        System.out.println(querykeyword);
        Map map = new HashMap();
        //创建高亮字段
        HighlightBuilder.Field field = new HighlightBuilder.Field("*")
                .preTags("<span style='color:red'>") //样式
                .postTags("</span>")
                .requireFieldMatch(false); //多字段高亮

        //创建检索对象
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.termQuery("name", querykeyword)) //term查询
                .withPageable(PageRequest.of((page - 1), limit)) //分页
                .withHighlightFields(field) //处理高亮显示
                .build();
        AggregatedPage<Dept> products = elasticsearchTemplate.queryForPage(nativeSearchQuery, Dept.class, new SearchResultMapper() {
            @Override
            public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                //创建集合存取product
                List<Dept> deptList = new ArrayList<>();
                //得到Hits集合
                SearchHit[] hits = searchResponse.getHits().getHits();
                //总条数
                long count = searchResponse.getHits().getTotalHits();
                map.put("count", count);

                for (SearchHit hit : hits) {
                    Dept dept = new Dept();
                    String id = hit.getId();
                    dept.setId(id);
                    //获取map
                    Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                    System.out.println(sourceAsMap);
                    //判断是否包含该字段
//                    String id = sourceAsMap.containsKey("id") ? sourceAsMap.get("id").toString() : "";
                    String name = sourceAsMap.containsKey("name") ? sourceAsMap.get("name").toString() : "";
                    String tel = sourceAsMap.containsKey("tel") ? sourceAsMap.get("tel").toString() : "";
                    String area = sourceAsMap.containsKey("area") ? sourceAsMap.get("area").toString() : "";

                    //给product赋值
//                    dept.setId(id);
                    dept.setName(name);
                    dept.setTel(tel);
                    dept.setArea(area);


                    //获取当前文档高亮字段map集合
                    Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                    System.out.println(highlightFields);
                    //name高亮显示，判断是否有name
                    if (!StringUtils.isEmpty(name)) {
                        if (highlightFields.get("name") != null) {
                            String heightName = highlightFields.get("name").getFragments()[0].toString();
                            dept.setName(heightName);
                        }
                    }
                    deptList.add(dept);
                }
                return new AggregatedPageImpl<>((List<T>) deptList);
            }
        });
        System.out.println(products.getContent());
        map.put("data", products.getContent());
        return map;
    }
}
